package pl.edu.mimuw.mas.agent.behaviour.deer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.edu.mimuw.mas.agent.DeerAgent;
import pl.edu.mimuw.mas.agent.behaviour.MutableTimedBehaviour;
import pl.edu.mimuw.mas.util.DeathHelper;
import pl.edu.mimuw.mas.util.Move;
import pl.edu.mimuw.mas.util.PositionHelper;
import pl.edu.mimuw.mas.util.Time;

public class MoveBehaviour extends MutableTimedBehaviour {
	
	private static final long serialVersionUID = 7308464433330551975L;
	
	private final DeerAgent myAgent;
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	public MoveBehaviour(DeerAgent a) {
		super(a, 1);
		
		myAgent = a;
	}
	
	protected void onTick() {
		DeerAgent deer = (DeerAgent) myAgent;
		
		// jeśli już nie żyje to kończe działanie
		if (DeathHelper.isDeerDead()) {
			this.stop();
			return;
		}
		// skoro żyje to idę dalej
		long step;
		if (deer.getFearSources().size() > 0) {
			step = Time.DEER_STEP_MIN; // skoro uciekam to z maksymalną prędkością
		} else {
			step = (long) (Math.random() * (Time.DEER_STEP_MAX - Time.DEER_STEP_MIN)) + Time.DEER_STEP_MIN;
		}
		boolean stop = Math.random() < 0.1; 

		if (!stop) {
			int vx = deer.getDest().x - deer.getPosition().x;
			int vy = deer.getDest().y - deer.getPosition().y;
			int max = Math.max(Math.abs(vx), Math.abs(vy));
			
			PositionHelper.move(deer, new Move((int)Math.round((double)vx / max), (int)Math.round((double)vy / max)));
		} else {
			PositionHelper.move(deer, new Move(0, 0));
		}
		setPeriod(step);
	}

}
